<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <a-row >
        <div :class="advanced ? null: 'fold'">
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="发送人"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-input v-model="queryParams.username"/>
              </a-form-item>
            </a-col>
          <template v-if="advanced">
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="创建时间"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <range-date @change="handleDateChange" ref="createTime"></range-date>
              </a-form-item>
              <a-form-item
                label="创建时间"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-range-picker :defaultValue="[moment(moment().startOf('month'),'YYYY-MM-DD HH:mm:ss'),moment(moment().endOf('day'),'YYYY-MM-DD HH:mm:ss')]"
                                showTime format="YYYY-MM-DD HH:mm:ss" :placeholder="['开始时间', '结束时间']" @change="handleDateChange" v-model="sendTime" style="margin-left: -2%;"/>
              </a-form-item>
            </a-col>
          </template>
        </div>
          <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
             <a @click="toggleAdvanced" style="margin-left: 8px">
              {{advanced ? '收起' : '展开'}}
              <a-icon :type="advanced ? 'up' : 'down'" />
            </a>
          </span>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button type="primary" ghost @click="add" v-hasPermission="'mail:view'">新增</a-button>
        <a-button @click="batchDelete" v-hasPermission="'user:delete'">删除</a-button>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :rowKey="record => record.id"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="'mail:view'" type="eye" theme="twoTone" twoToneColor="#42b983" @click="view(record)" title="发送"></a-icon>
          <a-badge v-hasNoPermission="'mail:send','mail:view'" status="warning" text="无权限"></a-badge>
        </template>
      </a-table>
    </div>
    <template>
      <a-cascader size="large" :fieldNames="{ label: 'name', value: 'code', children: 'itemsChildren' }" :options="options" @change="onChangeCascader" placeholder="Please select" />
    </template>
    <mail-send
      @close="handleMailAddClose"
      @success="handleMailAddSuccess"
     :mailAddVisiable="mailAddVisiable">
    </mail-send>
    <mail-detail
      ref="mailDetail"
      @close="handleMailViewClose"
      @success="handleMailAddSuccess"
     :mailViewVisiable="mailViewVisiable">
    </mail-detail>
  </a-card>
</template>

<script>
import moment from 'moment'
/* import MailSend from './MailSend'
import MailDetail from './MailDetail' */
import defaultPagination from '../../utils/common'

export default {
  name: 'Mail',
  components: {},
  data () {
    return {
      advanced: false,
      dataSource: [],
      selectedRowKeys: [],
      paginationInfo: null,
      pagination: defaultPagination,
      queryParams: {},
      sendTime: undefined,
      createTimeFrom: moment().startOf('month').format('YYYY-MM-DD HH:mm:ss'),
      createTimeTo: moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      mailAddVisiable: false,
      mailViewVisiable: false,
      loading: false
    }
  },
  computed: {
    columns () {
      return [{
        title: '标题',
        dataIndex: 'subject'
      }, {
        title: '收件人',
        dataIndex: 'receiver'
      }, {
        title: '抄送人',
        dataIndex: 'cc'
      }, {
        title: '发送时间',
        dataIndex: 'sendTime'
      }, {
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' }
      }]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    moment,
    toggleAdvanced () {
      this.advanced = !this.advanced
      if (!this.advanced) {
        this.queryParams.fieldName = ''
      }
    },
    handleMailAddSuccess () {
      this.mailAddVisiable = false
      this.$message.success('发送邮件成功')
      this.search()
    },
    handleMailAddClose () {
      this.mailAddVisiable = false
    },
    handleMailViewClose () {
      this.mailViewVisiable = false
    },
    view (record) {
      this.$refs.mailDetail.setFormValues(record)
      this.mailViewVisiable = true
    },
    add () {
      this.mailAddVisiable = true
    },
    handleDateChange (value, dateString) {
      if (value) {
        this.createTimeFrom = dateString[0]
        this.createTimeTo = dateString[1]
      }
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let logIds = that.selectedRowKeys.join(',')
          that.$delete('mail/' + logIds).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    exportExcel () {
      this.$export('mail/excel', {
        ...this.queryParams
      })
    },
    search () {
      this.queryParams.createTimeFrom = this.createTimeFrom
      this.queryParams.createTimeTo = this.createTimeTo
      this.restPagination()
      this.fetch({
        ...this.queryParams
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      this.restPagination()
      this.paginationInfo = null
      // 重置查询参数
      this.queryParams = {}
      // 清空时间选择
      this.sendTime = [moment(moment().startOf('month'), 'YYYY-MM-DD 00:00:00'), moment(moment().endOf('day'), 'YYYY-MM-DD HH:mm:ss')]
      this.createTimeFrom = moment().startOf('month').format('YYYY-MM-DD HH:mm:ss')
      this.createTimeTo = moment().endOf('day').format('YYYY-MM-DD HH:mm:ss')
      if (this.advanced) {
        this.$refs.sendTime.reset()
      }
      this.fetch()
    },
    restPagination () {
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
    },
    handleTableChange (pagination, filters, sorter) {
      this.paginationInfo = pagination
      this.fetch({
        ...this.queryParams
      })
    },
    fetch (params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      params.createTimeFrom = this.createTimeFrom
      params.createTimeTo = this.createTimeTo
      this.$get('mail/', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.loading = false
        this.dataSource = data.rows
        this.pagination = pagination
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import "../../../static/less/Common";
</style>
